(function() {
	var app = angular.module('WarningPersonalizedConfigApp', [ 'ui.bootstrap' ]);
	app
			.controller(
					'warningPersonalizedConfigController',
					function($http,$scope, $log, $uibModal) {
						$scope.insertComponent = {};
						$scope.deleteComponent = {};
						
						//临时保存当前配置下已经选的map
						$scope.selectedMap=[];
						
						//临时保存数据库获取当前配置下已经选的hostids
						$scope.selectedHostidsDb=new Array();
						
						//临时保存当前配置下已经选的节点name
						$scope.selectedNames=new Array;
						
						//存放当前ip选择窗口操作的监指标
						$scope.tdInputId;
						
						$scope.controller.selectedIpByDbOldEmp = [];

						$scope.zTreeObjNew;// 树状图子节点 数据
		
						var controller = this;
						controller.parameter = {};
						controller.queryParameter = "";
						this.warningConfigList = [];
						this.indexList = [];
						this.queryCondition = {
							"monitoringIndex" : "",
							"page" : 1,
							"size" : 5,
						};
						this.paginationInfo = {
							"maxSize" : 5,
							"totalPages" : 0,
							"totalElements" : 0
						};

						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							loadData();
						}

						// 跳转页数，回车事件
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}

						this.pageChanged = function() {
							loadData();
						}
						// 完成全选全部选事件
						$("#check_all").click(
								function() {
									$(".check_item").prop("checked",
											$(this).prop("checked"));
								});
						// 选中单个元素，如果单个元素选择满了，那么第一个主元素也被选中
						$(document)
								.on(
										"click",
										".check_item",
										function() {
											if ($(".check_item:checked").length == $(".check_item").length) {
												$("#check_all").prop("checked",
														true);
											}
											if ($(".check_item:checked").length == 0) {
												$("#check_all").prop("checked",
														false);
											}
										});
						
						//集合去重公共方法
						function arrayRemoveRepeat(array){
							var r=[];
							for(var i=0;i<array.length;i++){
								var flag=true;
								var temp=array[i];
								for(var j=0;j<r.length;j++){
									if(temp===r[j]){
										flag=false;
										break;
									}
								}
								if(flag){
									r.push(temp);
								}
							}
							return r;
						}
						

						
						// 新增配置
						this.insertConfig = function() {
							$scope.insertComponent = {};
							var modalInstanceAdd = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/configuration.management/insertWarningPersonalizedConfig.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'insertWarningPersonalizedConfigController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
							
							modalInstanceAdd.opened.then(function(){//模态窗口打开之后执行的函数  
								//加载ip树
								getTreeData(2,[]);
							}); 

							modalInstanceAdd.result.then(function(result) {
								loadData();
							});
						}
						
						
						//删除配置
						this.delConfig = function() {
							var basePath = $scope.getAppBasePath();
							var conditons =  new Array();
							var ids = "";
							$.each($(".check_item:checked"), function() {
								var id = "";   
								id = $(this).parents("tr").find("td:eq(1)").text();
								
								conditons.push(id);
								ids += $(this).parents("tr").find("td:eq(1)").text()+",";
							})
							ids = ids.substring(0,ids.length-1);
							// 如果没有选中的话
							if (conditons == "") {
								alert("请勾选需要删除的配置");
								return;
							} else {
							
								if (confirm("确认删除名为["
										+ ids + "]的配置吗?")) {
									// 保存后台调用
									$
											.ajax({
												type : "POST",
												url : basePath
														+ "/data/deleteWarningPersonalizedConfig",
												dataType : "json",
												contentType : "application/json",
												data : JSON.stringify(conditons),
												success : function(data) {
													alert("删除成功");
													loadData();
												}
											});

								}
							}
						}
						
	
						//保存配置
						this.saveConfig = function() {
							var basePath = $scope.getAppBasePath();
							var conditons = []; 
							var ids = "";
							$.each($(".check_item:checked"), function() {
								var contectsObj = new Object();   
								contectsObj.desc = $(this).parents("tr").find("td:eq(1)").text();
								contectsObj.kpi = $(this).parents("tr").find("td:eq(2)").text();
								contectsObj.warningLv1ValueLow = $(this).parents("tr").find("#lv1_low").val() || "";
								contectsObj.warningLv1ValueHigh = $(this).parents("tr").find("#lv1_high").val() || "";
								contectsObj.warningLv2ValueLow = $(this).parents("tr").find("#lv2_low").val() || "";
								contectsObj.warningLv2ValueHigh = $(this).parents("tr").find("#lv2_high").val() || "";
								contectsObj.warningLv3ValueLow = $(this).parents("tr").find("#lv3_low").val() || "";
								contectsObj.warningLv3ValueHigh = $(this).parents("tr").find("#lv3_high").val() || "";
								
								var ipMap =JSON.parse($(this).parents("tr").find(".hostids").val());
								var hostids="";
								for(var key in ipMap){
									hostids+=key+",";
								}
								
								contectsObj.hostids=hostids;
								
								conditons.push(contectsObj);
								ids += $(this).parents("tr").find("td:eq(1)").text()+",";

							})
							ids = ids.substring(0,ids.length-1);
							// 如果没有选中的话
							if(conditons != "0"){
							if (conditons == "" ) {
								alert("请勾选需要修改的配置");
								return;
							} else {
							
								if (confirm("确认修改名为["
										+ ids + "]的配置吗?")) {
									// 保存后台调用
									$
											.ajax({
												type : "POST",
												url : basePath
														+ "/data/updateWarningPersonalizedConfig",
												dataType : "json",
												contentType : "application/json",
												data : JSON.stringify(conditons),
												success : function(data) {
													alert("保存成功");
													loadData();
												}
											});

								}
							}
							}
						}
						
						// 选择IP弹窗
						this.selectIP = function(data) {
							$scope.selectIpList = {};
							var modalSelectIp = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/configuration.management/selectIP.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'updataWarningPersonalizedConfigController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
							modalSelectIp.opened.then(function(){//模态窗口打开之后执行的函数  
								//加载ip树
								getTreeData(1,data);
			            
							}); 
							
							modalSelectIp.result.then(function(result) {
								loadData();
							});
							
						}
						
						// 搜索事件
						this.search = function() {
							loadData();
						}

						// 重置事件
						this.reset = function() {
							this.queryCondition = {
									"monitoringIndex" : "",
									"page" : 1,
									"size" : 5,
								};
						}
						
						// 程序初期化
						this.init = function() {
							loadData();loadkpi();
							
						}
						this.init();

						
						//加载kpi
						function loadkpi(){
							var basePath = $scope.getAppBasePath();
							// 后台调用
							 $.ajax({
							 type : "POST",
							 url : basePath + "/data/getWarningPersonalizedMonitoringKpi",
							 dataType : "json",
							 contentType : "application/json",
							 //data : JSON.stringify(controller.parameter),
							 success : function(data) {
								 var jsonResult = angular.fromJson(data);
								 controller.indexList = jsonResult;
								 //手动刷新
								 $scope.$apply();  
							 	}
							 });
						}
						
						// 加载数据
						function loadData() {
							if ($(".check_item:checked").length == 0) {
								$("#check_all").prop("checked", false);
							}
							
							var basePath = $scope.getAppBasePath();
							// 参数获取
							controller.parameter.monitoringIndex = controller.queryCondition.monitoringIndex ||"";
							controller.parameter.page = controller.queryCondition.page;
							controller.parameter.size = controller.queryCondition.size;
							console.log(JSON.stringify(controller.parameter));
							// 后台调用
							 $.ajax({
							 type : "POST",
							 url : basePath + "/data/getWarningPersonalizedConfig",
							 dataType : "json",
							 contentType : "application/json",
							 data : JSON.stringify(controller.parameter),
							 success : function(data) {
							 var jsonResult = angular.fromJson(data);
							 //console.log(jsonResult);
							 controller.warningConfigList = jsonResult.list;
							 controller.paginationInfo.totalPages = jsonResult.pages;  //pages总页数
							 controller.paginationInfo.totalElements = jsonResult.total;  //total每页的条数
							 
							 //手动刷新
							 $scope.$apply();  
							 }
							 });

						}
						
						
						// 获取树状图数据
						function getTreeData(type,data) { //1:选择ip弹窗  2：新增弹窗
							selectedMap=data.ipMap;
							selectedHostidsDb=[];
							selectedNames=[];
							tdInputId=data.id;
							for(var key in selectedMap){
								selectedHostidsDb.push(parseInt(key));
								selectedNames.push(selectedMap[key]);
							}
						
							var basePath = $scope.getAppBasePath();
							var address = "";
							$
									.ajax({
										type : "POST",
										url : basePath + "/data/getIpTreeData",
										dataType : "json",
										contentType : "application/json",
										success : function(data) {
											var resultArrary = JSON.parse(data);

											var setting = {
												// 异步加载POST方法
												async : {
													enable : true,
													contentType : "application/json",
													dataType : "text",
													type : "post",
													url : basePath
															+ "/data/asyncGetIpTreeData",
													autoParam : [ "commentId" ],
													otherParam : [
															"hostId",-1														],
													dataFilter : ajaxDataFilter
												},
												// checkBox 效果
												check : {
													enable : true,
													chkStyle : "checkbox"
												},
												callback : {
													onAsyncSuccess : zTreeOnAsyncSuccess,
													onClick : zTreeOnClick,
													onExpand : zTreeOnExpand,// 点击节点前+号加载
													onCheck : zTreeOnCheck// 点击chckBox框加载
												},
											};

											function zTreeOnAsyncSuccess() {
											}
											// checked box 选中 取消时候，ip值的状态设置
											function zTreeOnCheck(event,
													treeId, treeNode) {
											}
											function zTreeBeforeAsync(treeId,
													treeNode) {
												return (treeNode.isParent == true);
											}
											;
											// 返回数据转成json
											function ajaxDataFilter(treeId,parentNode, responseData) {
												responseData = JSON.parse(responseData);
												// 获取已经被配置的Ip，并且设置checked为true
												
												for (var i = 0; i < responseData.length; i++) {
													for(var key in selectedMap){
														if (parseInt(responseData[i].id) ==parseInt(key)) {
																$scope.controller.selectedIpByDbOldEmp.push(responseData[i]);
																responseData[i].checked = "true";
														}
													}
												}

												return responseData;
											};
											if(type==1){
												var zTreeObj = $.fn.zTree.init(
														$("#selectIP"), setting,
														resultArrary);
												//默认展开根目录
												$("#selectIP_1_switch").click();
												
												//选中已经配置过的ips
												var treeObj = $.fn.zTree.getZTreeObj("selectIP");
												var tempArray=selectedNames;
												tempArray=arrayRemoveRepeat(tempArray);//去重
												for(var i=0;i<tempArray.length;i++){
													var node = treeObj.getNodeByParam("name", tempArray[i], null).tId+"_switch";//根据name属性获取树结构节点 tId
													//拿到节点后点击“+"调用异步加载方法
													$("#"+node).click();
												}
												
											}else{
												var zTreeObj = $.fn.zTree.init($("#warningSelectIP"), setting,resultArrary);
									
											}
			
											$scope.zTreeObjNew = zTreeObj;
							
											function zTreeOnExpand(event,
													treeId, treeNode) {
												var nodes = zTreeObj
														.getSelectedNodes();
												if (nodes.length > 0
														&& treeNode.level != 0
														&& treeNode.level != 1) {
													zTreeObj
															.reAsyncChildNodes(
																	nodes[0],
																	"refresh");
												}
											}
											function zTreeOnClick(event,
													treeId, treeNode) {
											}

											// 过滤ztree显示数据
											var hiddenNodes;
											function filter() {
												// 显示上次搜索后背隐藏的结点
												zTreeObj.showNodes(hiddenNodes);
												var _keywords = $("#keyword")
														.val();
												if (_keywords == null
														|| _keywords == "") {
													zTreeObj
															.showNodes(hiddenNodes);
												} else {
													var nodes = zTreeObj
															.getNodesByParamFuzzy(
																	"name",
																	_keywords,
																	null); // 根据节点数据的属性搜索，获取条件模糊匹配的节点数据
																			// JSON
																			// 对象集合,(keywords)模糊匹配只能针对
																			// String
																			// 类型的数据
													if (nodes.length > 0) {
														zTreeObj.selectNode(nodes[0]); // 会让节点自动滚到到可视区域内
													}

													// 查找不符合条件的叶子节点
													function filterFunc(node) {
														var _keywords = $(
																"#keyword")
																.val();
														if (node.isParent
																|| node.name
																		.indexOf(_keywords) != -1) {
															return false;
														} else {
															return true;
														}
													}
													;

													// 获取不符合条件的叶子结点
													hiddenNodes = zTreeObj
															.getNodesByFilter(filterFunc);

													// 隐藏不符合条件的叶子结点
													zTreeObj
															.hideNodes(hiddenNodes);
												}
											}
											;
										}
									});
						}

					})
			.controller(
					'insertWarningPersonalizedConfigController',
					function($scope, $uibModalInstance, $http, $log) {
						var basePath = $scope.getAppBasePath();
						var controller = this;
						this.indexList = [];
						this.kpiList = [];
						
						// 程序初期化
						this.init = function() {
						}
						this.init();
						
						
					
				
						
						$scope.save = function() {
							var basePath = $scope.getAppBasePath();
							// INSERT参数定义
							insertComponent = {
								"desc" : "",
								"kpi" : "",
								"warningLv1ValueLow" : "",
								"warningLv1ValueHigh" : "",
								"warningLv2ValueLow" : "",
								"warningLv2ValueHigh" : "",
								"warningLv3ValueLow" : "",
								"warningLv3ValueHigh" : "",
								"hostids":""
							};
							// INSERT值获取
							insertComponent.desc = $scope.$parent.insertComponent.monitoringIndex;
							insertComponent.kpi = $scope.$parent.insertComponent.kpi;
							insertComponent.warningLv1ValueLow = $scope.$parent.insertComponent.lv1Low;
							insertComponent.warningLv1ValueHigh = $scope.$parent.insertComponent.lv1High;
							insertComponent.warningLv2ValueLow = $scope.$parent.insertComponent.lv2Low;
							insertComponent.warningLv2ValueHigh = $scope.$parent.insertComponent.lv2High;
							insertComponent.warningLv3ValueLow = $scope.$parent.insertComponent.lv3Low;
							insertComponent.warningLv3ValueHigh = $scope.$parent.insertComponent.lv3High;
							
							
							//提交验证
							if(insertComponent.desc=="" || insertComponent.desc==undefined){
								alert("监控指标还没有填写！");
								return;
							}
							if(insertComponent.kpi=="" || insertComponent.kpi==undefined){
								alert("请填写kpi！");
								return;
							}
							if(
									(insertComponent.warningLv1ValueLow=="" || insertComponent.warningLv1ValueLow==undefined)
									&& (insertComponent.warningLv2ValueLow=="" || insertComponent.warningLv2ValueLow==undefined)
									&& (insertComponent.warningLv3ValueLow=="" || insertComponent.warningLv3ValueLow==undefined)
							){
								alert("至少设定一个管控级别的下限！");
								return;
							}
							//管控级别可以不设定，可以只设定下限但是不能只设上限不设上限
							if(insertComponent.warningLv1ValueHigh !="" && insertComponent.warningLv1ValueHigh!=undefined){
								if(insertComponent.warningLv1ValueLow=="" || insertComponent.warningLv1ValueLow==undefined){
									alert("管控级别1的下限缺失！");
									return;
								}
							}
							if(insertComponent.warningLv2ValueHigh !="" && insertComponent.warningLv2ValueHigh!=undefined){
								if(insertComponent.warningLv2ValueLow=="" || insertComponent.warningLv2ValueLow==undefined){
									alert("管控级别2的下限缺失！");
									return;
								}
							}
							if(insertComponent.warningLv3ValueHigh !="" && insertComponent.warningLv3ValueHigh!=undefined){
								if(insertComponent.warningLv3ValueLow=="" || insertComponent.warningLv3ValueLow==undefined){
									alert("管控级别3的下限缺失！");
									return;
								}
							}
							
							//获取选中的ip
				            var treeObj=$.fn.zTree.getZTreeObj("warningSelectIP"),
				            selectedIp=treeObj.getCheckedNodes(true),
				            hostids=""; 
							if(selectedIp.length==0){
								alert("请选择ip后保存！");
								return;
							}
							//获取选中ip节点
							for (var i = 0; i < selectedIp.length; i++) {
								if (selectedIp[i].chidren == undefined && selectedIp[i].isParent == false) 
								{
									hostids+=selectedIp[i].id + ",";
								}
							}
				            
							insertComponent.hostids = hostids;
							
							// 后台调用
							$.ajax({
								type : "POST",
								url : basePath + "/data/insertWarningPersonalizedConfig",
								dataType : "json",
								contentType : "application/json",
								data : JSON.stringify(insertComponent),
								success : function(data) {
									$uibModalInstance.close();
									alert("插入成功");
								}
							});
							
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					})
					
				.controller(
					'updataWarningPersonalizedConfigController',
					function($scope, $uibModalInstance, $http, $log) {
						var basePath = $scope.getAppBasePath();
						var controller = this;
						this.indexList = [];
						this.kpiList = [];
						
						// 程序初期化
						this.init = function() {
						}
						this.init();
						
						//两个集合取差集公共方法
						function subSet(arr1,arr2){
							var len=arr1.length;
							var arr=[];
							while(len--){
								if(arr2.indexOf(arr1[len])<0){
									arr.push(arr1[len]);
								}
							}
							
							return arr;
						}
						
						//集合转String“，”隔开的公共方法
						function ArrayToString(arr){
							var len=arr.length;
							var str="";
							for(var i=0;i<len;i++){
								if(arr[i]!=null && arr[i]!="" && arr[i]!=undefined ){
									str+=arr[i]+",";
								}
							} 
							
							return str;
						}
						
						//选择ip点击确定事件
						$scope.save = function() {
							
							//获取选中的ip
				            var treeObj=$.fn.zTree.getZTreeObj("selectIP"),
				            selectedIp=treeObj.getCheckedNodes(true),
				            hostids=new Array(); 
							if(selectedIp.length==0){
								alert("请选择ip后保存！");
								return;
							}
							//获取选中ip节点只取末级节点
							for (var i = 0; i < selectedIp.length; i++) {
								if (selectedIp[i].chidren == undefined && selectedIp[i].isParent == false) 
								{
									hostids.push(selectedIp[i].id);
								}
							}
							//判断新增的和删除的ip
							var deletedHostids=subSet(selectedHostidsDb,hostids); //保存删除掉的ip hostid
							var addHostids=subSet(hostids,selectedHostidsDb); 	//保存新增的ip hostid

							var basePath = $scope.getAppBasePath();
			
						
							var contectsObj = new Object();   
							contectsObj.desc = $("#tdInput_"+tdInputId).parents("tr").find("td:eq(1)").text();
							contectsObj.kpi = $("#tdInput_"+tdInputId).parents("tr").find("td:eq(2)").text();
							contectsObj.warningLv1ValueLow = $("#tdInput_"+tdInputId).parents("tr").find("#lv1_low").val() || "";
							contectsObj.warningLv1ValueHigh =$("#tdInput_"+tdInputId).parents("tr").find("#lv1_high").val() || "";
							contectsObj.warningLv2ValueLow = $("#tdInput_"+tdInputId).parents("tr").find("#lv2_low").val() || "";
							contectsObj.warningLv2ValueHigh =$("#tdInput_"+tdInputId).parents("tr").find("#lv2_high").val() || "";
							contectsObj.warningLv3ValueLow = $("#tdInput_"+tdInputId).parents("tr").find("#lv3_low").val() || "";
							contectsObj.warningLv3ValueHigh =$("#tdInput_"+tdInputId).parents("tr").find("#lv3_high").val() || "";
							
							
							contectsObj.hostids=ArrayToString(addHostids);;
							contectsObj.deletedHostids=ArrayToString(deletedHostids);;
						
		
							//提交验证
							if(contectsObj.desc=="" || contectsObj.desc==undefined){
								alert("监控指标还没有填写！");
								return;
							}
							if(contectsObj.kpi=="" || contectsObj.kpi==undefined){
								alert("请填写kpi！");
								return;
							}
							if(
									(contectsObj.warningLv1ValueLow=="" || contectsObj.warningLv1ValueLow==undefined)
									&& (contectsObj.warningLv2ValueLow=="" || contectsObj.warningLv2ValueLow==undefined)
									&& (contectsObj.warningLv3ValueLow=="" || contectsObj.warningLv3ValueLow==undefined)
							){
								alert("至少设定一个管控级别的下限！");
								return;
							}
							//管控级别可以不设定，可以只设定下限但是不能只设上限不设上限
							if(contectsObj.warningLv1ValueHigh !="" && contectsObj.warningLv1ValueHigh!=undefined){
								if(contectsObj.warningLv1ValueLow=="" || contectsObj.warningLv1ValueLow==undefined){
									alert("管控级别1的下限缺失！");
									return;
								}
							}
							if(contectsObj.warningLv2ValueHigh !="" && contectsObj.warningLv2ValueHigh!=undefined){
								if(contectsObj.warningLv2ValueLow=="" || contectsObj.warningLv2ValueLow==undefined){
									alert("管控级别2的下限缺失！");
									return;
								}
							}
							if(contectsObj.warningLv3ValueHigh !="" && contectsObj.warningLv3ValueHigh!=undefined){
								if(contectsObj.warningLv3ValueLow=="" || contectsObj.warningLv3ValueLow==undefined){
									alert("管控级别3的下限缺失！");
									return;
								}
							}
							
							
							
							
									// 保存后台调用
									$.ajax({
												type : "POST",
												url : basePath
														+ "/data/updateWarningPersonalizedSelectIps",
												dataType : "json",
												contentType : "application/json",
												data : JSON.stringify(contectsObj),
												success : function(data) {
													$uibModalInstance.close();
													alert("保存成功");
												}
											});
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					}
					
				)
			
})();